package com.taotao.order.interceptor;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taoato.sso.service.UserLoginService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.common.util.JsonUtils;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbUser;
import com.taotao.trolley.service.CartService;

/**
 * 进入订单页面时需要判断用户是否登录
 * 
 * @author Administrator
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Value("${TOKEN_KEY}")
	private String TOKEN_KEY;

	@Autowired
	private UserLoginService userService;
	
	@Autowired
	private CartService cartService;

	@Value("${SSO_URL}")
	private String SSO_URL;
	
	@Value("${CART_KEY}")
	private String CART_KEY;
	
	// 进入目标方法之前调用
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// 判断用户是否登录
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY, true);
		if (StringUtils.isEmpty(token)) {
			response.sendRedirect(SSO_URL+"/page/login?url=" + request.getRequestURL().toString());
			return false;
		}
		// 引入sso服务， 根据token获取用户信息
		TaotaoResult result = userService.getToken(token);
		
		TbUser user = (TbUser)result.getData();
		// 判断用户是否过期
		if (result.getStatus() == 400) {
			response.sendRedirect(SSO_URL+"/page/login?url=" + request.getRequestURL().toString());
			return false;
		}
		//如果用户登录成功则合并cookie中的订单
		String cookieValue = CookieUtils.getCookieValue(request, CART_KEY, true);
		if(StringUtils.isNotBlank(cookieValue)) {
			List<TbItem> list = JsonUtils.jsonToList(cookieValue, TbItem.class);
			Iterator<TbItem> iterator = list.iterator();
			while (iterator.hasNext()) {
				TbItem tbItem = (TbItem) iterator.next();
				cartService.addItemCart(tbItem, tbItem.getNum(), user.getId());
			}
		}
		
		request.setAttribute("USER_INFO", result.getData());
		return true;
	}

	// 进入目标方法，返回modelAndView之前调用
	// 共用变量的设置
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	// 在目标方法之后调用 ，渲染页面之前
	// 异常处理，清理工作
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}
}
